Ch4 Ownership
2026-02-25 ใน The rust programming language 3rd edition(online document)1 Ownership
The undefined problem
- There is a problem of undefined behavior which cause serious security issues, esp in C, C++.
- Rust's complier doesn't permitt this bug to the final program.
Normal value will be kept as frame stacks
- Normal values types(i32, f64, bool, array, etc. - any data type that aren't kept in heap) will be kept as frame stacks
- When the new variable value is set with another variable, Rust will copy another value to the new variable frame stack.
- when the section{...} is deprecated, the variables in the section will also be deprecated.
Pointer as ownership(no 2 owner at the same time)
- For the values created with Box, String and Vec, they will be kept in the memory heap which is the section that has infinite memory size(allocated by rust)
- The variable will link to the array in heap with pointer, but not keep the value in itself as frame stack.
- The rule is that one array box in heap can have only one variable that is linked with at one time. Rust call this as an ownership.
- When the value from one variable (that link with array in heap) is set to another variable, the ownership of heap array will allocated to the new one, and the prior variable will be deprecated. It is the changing of ownership.
- "Changing of ownership" will decrease memory requirement and increase performance.(if rust keep copying of array to the new variable, eg. 1GB size data, the memory required will expand a lot unnecessarily, and deteriorates performance.)
- The most important thing is that Rust doesn't allow more than one ownership to one heap array present at a time(but only the last variable that's set to), unlike in C, C++. Because if that heap array was modified and there are many owner, all owner value will later changed unexpectedly, and cause a program to work in unexpected way, or even be exploited.
- It require very sophisticated mathematics algorithm of Rust to check the ownership in compliation.
- Ownership is like when you hold the company's balance sheets in your hand, no one can edit, change or even read it in the moment, they have to take an ownership first, which is very safe for the data and usability.
Borrowing
- & = reference = borrowing
- * = dereference (1 step more to the original)